//
//  SNHttpTool.m
//  顺农有机
//
//  Created by 冯贺 on 2018/1/12.
//  Copyright © 2018年 冯贺. All rights reserved.
//

#import "SNHttpTool.h"
#import "AFNetworking.h"

#define kTimeoutInterval 30
MBProgressHUD *hud;
@implementation SNHttpTool

+(void)getWithUrl:(NSString *)url params:(NSMutableDictionary *)params View:(UIView *)view success:(void (^)(NSDictionary *, NSString *))success failure:(void (^)(NSHTTPURLResponse *))failure{
    
    [IANshowLoading showLoadingForView:view allowUserInteraction:YES];
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    AFHTTPSessionManager * manager =[AFHTTPSessionManager  manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.requestSerializer.timeoutInterval = kTimeoutInterval;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSString * requestUrl = [tHost_URL stringByAppendingString:url];
    DLog(@"requesturl:%@",requestUrl);
    [manager GET:requestUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [IANshowLoading hideLoadingForView:view];
        if (success) {
            
            NSString * message = responseObject[@"result_code"];
            
            success (responseObject,message);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            [IANshowLoading hideLoadingForView:view];
            DLog(@"Error: %@", error);
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            failure(responses);
            NSLog(@"====================%ld",(long)responses.statusCode);
            if (responses.statusCode != 518) {
                [SMGlobalMethod showMessage:@"网络请求失败,请稍后重试"];
                //自己想要进行的操作
            }else{
                [SNAccountTool removeUserInfo];
        
            }
        }
    }];
}
+ (void)postWithUrl:(NSString *)url params:(NSMutableDictionary *)params View:(UIView *)view success:(void (^)(NSDictionary *, NSString *))success failure:(void (^)(NSHTTPURLResponse *))failure{

    [IANshowLoading showLoadingForView:view allowUserInteraction:YES];
    
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    AFHTTPSessionManager * manager =[AFHTTPSessionManager  manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.requestSerializer.timeoutInterval = kTimeoutInterval;
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSString * requestUrl = [tHost_URL stringByAppendingString:url];
    DLog(@"url:%@",requestUrl);
    [manager POST:requestUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [IANshowLoading hideLoadingForView:view];
        if (success) {
            
            NSString * message = responseObject[@"result_code"];
            
            success (responseObject,message);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [IANshowLoading hideLoadingForView:view];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        failure(responses);
        NSLog(@"===============网络请求错误码是:%ld",(long)responses.statusCode);
        [SMGlobalMethod showMessage:@"后台出错了"];
//        if (responses.statusCode != 518) {
//            [SMGlobalMethod showMessage:@"网络请求失败,请稍后重试"];
//            //自己想要进行的操作
//        }else{
//            [SNAccountTool removeUserInfo];
//
//        }
        
    }];
}

+(void)updateWithUrl:(NSString *)url params:(NSMutableDictionary *)params imageArr:(NSArray *)imgArr  View:(UIView *)view success:(void (^)(NSDictionary *))success failure:(void (^)(NSHTTPURLResponse *))failure{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.label.text = @"正在上传...";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    NSString * requestUrl = [tHost_URL stringByAppendingString:url];
    DLog(@"url:%@",requestUrl);
    [manager POST:requestUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        
        for (UIImage * img in imgArr) {
            NSData *data = UIImageJPEGRepresentation(img,0.7);
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印上传进度
        CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        DLog(@"%.2lf%%", progress);
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = progress;
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            //请求成功
//            DLog(@"请求成功：%@",responseObject);
            if (![responseObject[@"code"] isEqualToString:@"ok"]) {
                hud.label.text = @"发表说说失败";
                [hud hideAnimated:YES afterDelay:0.3];
                return;
            }
            hud.label.text = @"发表说说成功";
            [hud hideAnimated:YES afterDelay:0.3];
            success(responseObject);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        DLog(@"请求失败：%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES afterDelay:0.3];
        });
    }];
    
    
}



+(void)getWithZhenUrl:(NSString *)url params:(NSMutableDictionary *)params View:(UIView *)view success:(void (^)(NSDictionary *, NSString *))success failure:(void (^)(NSHTTPURLResponse *))failure{
    
    [IANshowLoading showLoadingForView:view allowUserInteraction:YES];
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    AFHTTPSessionManager * manager =[AFHTTPSessionManager  manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.requestSerializer.timeoutInterval = kTimeoutInterval;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [IANshowLoading hideLoadingForView:view];
        if (success) {
            
            NSString * message = responseObject[@"resultcode"];
            
            success (responseObject,message);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            [IANshowLoading hideLoadingForView:view];
            DLog(@"Error: %@", error);
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            failure(responses);
            NSLog(@"====================%ld",(long)responses.statusCode);
            if (responses.statusCode != 518) {
                [SMGlobalMethod showMessage:@"网络请求失败,请稍后重试"];
                //自己想要进行的操作
            }else{
                [SNAccountTool removeUserInfo];
                
            }
        }
    }];
}









@end
